package com.example.ymm.modules1.service.impl.hl.ex;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.dto.HengLiConstants;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.ex.ExCategory;
import com.example.ymm.modules1.entity.hl.ex.ExQuestion;
import com.example.ymm.modules1.entity.hl.ex.ExQuestionOption;
import com.example.ymm.modules1.entity.hl.ex.ExTeam;
import com.example.ymm.modules1.mapper.ex.ExQuestionMapper;
import com.example.ymm.modules1.query.hl.ex.ExQuestionOptionQueryCriteria;
import com.example.ymm.modules1.query.hl.ex.ExQuestionQueryCriteria;
import com.example.ymm.modules1.service.dto.common.ExcelData;
import com.example.ymm.modules1.service.dto.heng.ex.*;
import com.example.ymm.modules1.service.hl.ex.ExCategoryService;
import com.example.ymm.modules1.service.hl.ex.ExQuestionOptionService;
import com.example.ymm.modules1.service.hl.ex.ExQuestionService;
import com.example.ymm.modules1.service.hl.ex.ExTeamService;
import com.example.ymm.util.ArrayListSplitter;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//@Transactional
@Slf4j
@DS("slave2")
public class ExQuestionServiceImpl extends BaseServiceImpl<ExQuestionMapper, ExQuestion> implements ExQuestionService {

    @Autowired
    ExQuestionOptionService exQuestionOptionService;
    @Autowired
    ExCategoryService exCategoryService;
    @Autowired
    private ExTeamService exTeamService;

    @Override
    public TableList<ExQuestion> list(ExQuestionQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        List<ExQuestion> questions = queryList(criteria);
        List<String> questionIds=new ArrayList<>();
        //性格测试题id
        for (ExQuestion question : questions) {
            if(question.getType().equals(HengLiConstants.xing_ge_question)){
                questionIds.add(question.getQuestionId());
            }
        }
        ExQuestionOptionQueryCriteria c2=new ExQuestionOptionQueryCriteria();
        c2.setQuestionIdIn(questionIds);
        List<ExQuestionOption> exQuestionOptions = exQuestionOptionService.queryAll(c2);
        for (ExQuestion question : questions) {
            List<String> optionTitle=new ArrayList<>();
            for (ExQuestionOption exQuestionOption : exQuestionOptions) {
                if(question.getQuestionId().equals(exQuestionOption.getQuestionId())){
                    optionTitle.add(exQuestionOption.getLetter()+exQuestionOption.getTitle());
                }
            }
            if(UtilValidate.isEmpty(question.getTitle())&&UtilValidate.isNotEmpty(optionTitle)){
                question.setTitle(String.join(";",optionTitle));
            }
        }
        PageInfo<ExQuestion> pageInfo = new PageInfo<>(questions);
        TableList<ExQuestion> tableList = new TableList(pageInfo);
        return tableList;
    }

    public List<ExQuestion> queryAll(ExQuestionQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExQuestion.class, criteria);
        predicate.orderByAsc("sort");
        List<ExQuestion> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public List<String> importQuestionFn(ImportQuestionDataDto dto) {
        List<String> msg = new ArrayList<String>();
        List<ImQuestionItemDto> list = dto.getList();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        String duoType="多选题",danType="单选题";
        for(ImQuestionItemDto imQuestionItemDto:list){
            String title = imQuestionItemDto.getTitle().trim();
            String value = imQuestionItemDto.getValue().trim();
            if(UtilValidate.isEmpty(title)&&UtilValidate.isEmpty(value)){
                imQuestionItemDto.setTitle(null);
                imQuestionItemDto.setValue(null);
            }
        }
        // 拆分数组
        List<List<ImQuestionItemDto>> subLists = ArrayListSplitter.splitListByNullProperty(list);

        List<ExQuestion> questions=new ArrayList<>();
        String letter_str="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        // 输出结果
        for (int i = 0; i < subLists.size(); i++) {
            List<ImQuestionItemDto> imQuestionItemDtos = subLists.get(i);
            ExQuestion exQuestion = new ExQuestion();
            List<ExQuestionOption> exQuestionOptions = new ArrayList<>();
            for (int j = 0; j < imQuestionItemDtos.size(); j++) {
                ImQuestionItemDto imQuestionItemDto = imQuestionItemDtos.get(j);
                String title = imQuestionItemDto.getTitle().trim();
                String value = imQuestionItemDto.getValue().trim();

                if(value.equals(duoType)||value.equals(danType)){
                    exQuestion.setType(value);
                }
                if(title.equals("题目")){
                    exQuestion.setTitle(value);
                }
                if(title.equals("解析")){
                    exQuestion.setExplain(value);
                }
                if(title.equals("正确答案")){
                    exQuestion.setAnswer(value);
                }


                /**
                 * 选项-----
                 */
                if(UtilValidate.isNotEmpty(title)&&title.length()==1&&letter_str.contains(title)){
                    ExQuestionOption exQuestionOption = new ExQuestionOption();
                    exQuestionOption.setTitle(value);
                    exQuestionOption.setLetter(title);
                    exQuestionOption.setSort(j+1);
                    String answer = exQuestion.getAnswer();
                    if(UtilValidate.isNotEmpty(answer)&&answer.contains(title)){
                        exQuestionOption.setIsTrue(1);
                    }
                    exQuestionOptions.add(exQuestionOption);

                }
                exQuestion.setOptions(exQuestionOptions);

            }
            exQuestion.setSort(i);
            questions.add(exQuestion);
        }


        //保存数据
        questions.forEach(exQuestion -> {
            saveOrUpdate(exQuestion);
            exQuestion.getOptions().forEach(exQuestionOption -> {
                exQuestionOption.setQuestionId(exQuestion.getQuestionId());
            });
            exQuestionOptionService.saveOrUpdateBatch(exQuestion.getOptions());
        });


        return msg;
    }


    @Override
    public List<String> importQuestionSortFn(ImportQuestionDataDto dto) {
        List<String> msg = new ArrayList<String>();
        List<ImQuestionItemDto> list = dto.getList();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        String duoType="多选题",danType="单选题";
        for(ImQuestionItemDto imQuestionItemDto:list){
            String title = imQuestionItemDto.getTitle().trim();
            String value = imQuestionItemDto.getValue().trim();
            if(UtilValidate.isEmpty(title)&&UtilValidate.isEmpty(value)){
                imQuestionItemDto.setTitle(null);
                imQuestionItemDto.setValue(null);
            }
        }
        // 拆分数组
        List<List<ImQuestionItemDto>> subLists = ArrayListSplitter.splitListByNullProperty(list);


        // 输出结果
        for (int i = 0; i < subLists.size(); i++) {
            List<ImQuestionItemDto> imQuestionItemDtos = subLists.get(i);
            ExQuestion exQuestion = new ExQuestion();
            List<ExQuestionOption> exQuestionOptions = new ArrayList<>();
            for (int j = 0; j < imQuestionItemDtos.size(); j++) {
                ImQuestionItemDto imQuestionItemDto = imQuestionItemDtos.get(j);
                String title = imQuestionItemDto.getTitle().trim();
                String value = imQuestionItemDto.getValue().trim();

                if(value.equals(duoType)||value.equals(danType)){
                    exQuestion.setType(value);
                }
                if(title.equals("题目")){
                    exQuestion.setTitle(value);

                    //修改排序

                    ExQuestionQueryCriteria c2=new ExQuestionQueryCriteria();
                    c2.setTitle(value);
                    List<ExQuestion> questions = queryAll(c2);
                    if(UtilValidate.isNotEmpty(questions)){
                        ExQuestion exQuestion1 = questions.get(0);
                        exQuestion1.setSort(i+1);
                        saveOrUpdate(exQuestion1);
                    }
                }

            }
        }




        return msg;
    }

    @Override
    public List<String> importQuestionFn2(ImportQuestionDataDto2 dto) {
        List<String> msg = new ArrayList<String>();
        List<ImQuestionItemDto2> list = dto.getList();
        List<ExQuestion> add_list =new ArrayList<>();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        Map<String,Integer> map=new HashMap<>();
        map.put("A",1);map.put("B",2);map.put("C",3);map.put("D",4);
        for(ImQuestionItemDto2 dto2:list){
            String title = dto2.getTitle().trim();
            String explain = dto2.getExplain().trim();
            String answer = dto2.getAnswer();
            String type = dto2.getType();
            if(UtilValidate.isNotEmpty(title)){
                ExQuestion exQuestion = new ExQuestion();
                exQuestion.setTitle(title);
                exQuestion.setExplain(explain);
                exQuestion.setAnswer(answer);
                exQuestion.setType(type);
                saveOrUpdate(exQuestion);

                List<ExQuestionOption> exQuestionOptions = new ArrayList<>();
                String a = dto2.getA();
                String b = dto2.getB();
                String c = dto2.getC();
                String d = dto2.getD();
                ExQuestionOption option1 = new ExQuestionOption();
                option1.setQuestionId(exQuestion.getQuestionId());
                option1.setSort(1);
                if(UtilValidate.isNotEmpty(answer)&&answer.contains("A")){
                    option1.setIsTrue(1);
                }
                option1.setLetter("A");
                option1.setTitle(a);
                exQuestionOptions.add(option1);

                ExQuestionOption option2 = new ExQuestionOption();
                option2.setQuestionId(exQuestion.getQuestionId());
                option2.setSort(2);
                if(UtilValidate.isNotEmpty(answer)&&answer.contains("B")){
                    option2.setIsTrue(1);
                }
                option2.setLetter("B");
                option2.setTitle(b);
                exQuestionOptions.add(option2);

                ExQuestionOption option3 = new ExQuestionOption();
                option3.setQuestionId(exQuestion.getQuestionId());
                option3.setSort(3);
                if(UtilValidate.isNotEmpty(answer)&&answer.contains("C")){
                    option3.setIsTrue(1);
                }
                option3.setLetter("C");
                option3.setTitle(c);
                exQuestionOptions.add(option3);

                ExQuestionOption option4 = new ExQuestionOption();
                option4.setQuestionId(exQuestion.getQuestionId());
                option4.setSort(4);
                if(UtilValidate.isNotEmpty(answer)&&answer.contains("D")){
                    option4.setIsTrue(1);
                }
                option4.setLetter("D");
                option4.setTitle(d);
                exQuestionOptions.add(option4);
                System.out.println(exQuestionOptions);
                exQuestionOptionService.saveOrUpdateBatch(exQuestionOptions);
            }
        }

        return msg;
    }


    @Override
    public List<String> importXinGeQuestionFn(ImportXinGeQuestionDataDto dto) {
        List<String> msg = new ArrayList<String>();
        List<ImXinGeQuestionDto> list = dto.getList();
        List<ExQuestion> add_list =new ArrayList<>();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        Map<String,Integer> map=new HashMap<>();
        map.put("C",1);map.put("P",2);map.put("S",3);map.put("M",4);
        for(ImXinGeQuestionDto dto2:list){

            String type = dto2.getType();
            ExQuestion exQuestion = new ExQuestion();

            exQuestion.setType(type);
            saveOrUpdate(exQuestion);

            List<ExQuestionOption> exQuestionOptions = new ArrayList<>();
            String c = dto2.getC();
            String p = dto2.getP();
            String s = dto2.getS();
            String m = dto2.getM();
            ExQuestionOption option1 = new ExQuestionOption();
            option1.setQuestionId(exQuestion.getQuestionId());
            option1.setSort(1);
            option1.setTitle(c);
            option1.setLetter("C");

            exQuestionOptions.add(option1);

            ExQuestionOption option2 = new ExQuestionOption();
            option2.setQuestionId(exQuestion.getQuestionId());
            option2.setSort(2);
            option2.setLetter("P");
            option2.setTitle(p);
            exQuestionOptions.add(option2);

            ExQuestionOption option3 = new ExQuestionOption();
            option3.setQuestionId(exQuestion.getQuestionId());
            option3.setSort(3);

            option3.setLetter("S");
            option3.setTitle(s);
            exQuestionOptions.add(option3);

            ExQuestionOption option4 = new ExQuestionOption();
            option4.setQuestionId(exQuestion.getQuestionId());
            option4.setSort(4);

            option4.setLetter("M");
            option4.setTitle(m);
            exQuestionOptions.add(option4);
            System.out.println(exQuestionOptions);
            exQuestionOptionService.saveOrUpdateBatch(exQuestionOptions);
        }

        return msg;
    }

    @Override
    public List<String> importQuestionFn3(List<ImQuestionGroupDto> list) {
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        List<String> msg = new ArrayList<String>();
        List<ExQuestion> questions=new ArrayList<>();
        String letter_str="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String duoType="多选题",danType="单选题";

        // 输出结果
        for (int i = 0; i < list.size(); i++) {
            ImQuestionGroupDto imQuestionItemDtos = list.get(i);
            List<ExcelData> items = imQuestionItemDtos.getItems();
            ExQuestion exQuestion = new ExQuestion();
            exQuestion.setImg(imQuestionItemDtos.getImg());
            List<ExQuestionOption> exQuestionOptions = new ArrayList<>();

            for (int j = 0; j <items.size() ; j++) {

                ExcelData excelData = items.get(j);
                if(UtilValidate.isEmpty(excelData.getValue())){
                    System.out.println(excelData);
                }
                String title = excelData.getTitle().trim();
                String value = "";
                if(UtilValidate.isNotEmpty(excelData.getValue())){
                    value = excelData.getValue().trim();
                }

                if(value.equals(duoType)||value.equals(danType)){
                    exQuestion.setType(value);
                }
                if(title.equals("题目")){
                    exQuestion.setTitle(value);
                }
                if(title.equals("解析")){
                    exQuestion.setExplain(value);
                }
                if(title.equals("正确答案")){
                    exQuestion.setAnswer(value);
                }
                /**
                 * 选项-----
                 */
                if(UtilValidate.isNotEmpty(title)&&title.length()==1&&letter_str.contains(title)){
                    ExQuestionOption exQuestionOption = new ExQuestionOption();
                    exQuestionOption.setTitle(value);
                    exQuestionOption.setLetter(title);
                    exQuestionOption.setSort(j+1);
                    String answer = exQuestion.getAnswer();
                    if(UtilValidate.isNotEmpty(answer)&&answer.contains(title)){
                        exQuestionOption.setIsTrue(1);
                    }
                    exQuestionOptions.add(exQuestionOption);
                }
            }
            exQuestion.setOptions(exQuestionOptions);
            questions.add(exQuestion);
        }
//        System.out.println(questions);
        //保存数据
        questions.forEach(exQuestion -> {
            saveOrUpdate(exQuestion);
            exQuestion.getOptions().forEach(exQuestionOption -> {
                exQuestionOption.setQuestionId(exQuestion.getQuestionId());
            });
            exQuestionOptionService.saveOrUpdateBatch(exQuestion.getOptions());
        });
        return msg;
    }

    @Override
    public void questionSave(ExQuestion question) {
        if(UtilValidate.isEmpty(question.getTitle())){
            throw new YmException("请输入题目名称!");
        }
//        if(UtilValidate.isNotEmpty(question.getQuestionId())){
//            updateById(question);
//        }else{
//            saveOrUpdate(question);
//        }

        if(UtilValidate.isNotEmpty(question.getCategoryId())){
            ExCategory category = exCategoryService.getById(question.getCategoryId());
            if(UtilValidate.isNotEmpty(category)){
                question.setCategoryName(category.getCategoryName());
                if(!"0".equals(category.getPid())){
                    ExCategory p_category = exCategoryService.getById(category.getPid());
                    if(UtilValidate.isNotEmpty(p_category)&&UtilValidate.isNotEmpty(p_category.getTeamId())){
                        question.setTeamId(p_category.getTeamId());
                    }
                }
            }

        }
        if(UtilValidate.isNotEmpty(question.getTeamId())){
            ExTeam team = exTeamService.getById(question.getTeamId());
            if(UtilValidate.isNotEmpty(team)){
                question.setTeamName(team.getDeptName());
            }
        }
        saveOrUpdate(question);

        List<ExQuestionOption> options = question.getOptions();
        if(UtilValidate.isNotEmpty(options)){
            LambdaQueryWrapper<ExQuestionOption> queryWrapper = new LambdaQueryWrapper<ExQuestionOption>();
            queryWrapper.eq(ExQuestionOption::getQuestionId, question.getQuestionId());
            exQuestionOptionService.remove(queryWrapper);
            for (int i = 0; i < options.size(); i++) {
                ExQuestionOption exQuestionOption = options.get(i);
                exQuestionOption.setQuestionId(question.getQuestionId());
                exQuestionOption.setSort(i+1);
                exQuestionOptionService.saveOrUpdate(exQuestionOption);
            }
        }
    }


    @Override
    public void questionBatchCategoryId(String categoryId, String questionIds) {
        ExCategory category = exCategoryService.getById(categoryId);
        String teamId = category.getTeamId();
        if(UtilValidate.isEmpty(teamId)){
            ExCategory p_category = exCategoryService.getById(category.getPid());
            if(UtilValidate.isNotEmpty(p_category)){
                 teamId=p_category.getTeamId();
            }
        }
        String teamName=null;
        if(UtilValidate.isNotEmpty(teamId)){
            ExTeam byId = exTeamService.getById(teamId);
            if(UtilValidate.isNotEmpty(byId)){
                teamName=byId.getDeptName();
            }
        }
        String[] split = questionIds.split(",");
        for (String id : split) {
            ExQuestion question=new ExQuestion();
            question.setCategoryId(categoryId);
            question.setCategoryName(category.getCategoryName());
            question.setQuestionId(id);
            question.setTeamId(teamId);
            question.setTeamName(teamName);
            updateById(question);
        }
    }

    @Override
    public Long countByCategoryId(String categoryId) {
        ExQuestionQueryCriteria criteria=new ExQuestionQueryCriteria();
        criteria.setCategoryId(categoryId);
        return baseMapper.countByCategoryId(criteria);
    }

    @Override
    public List<ExQuestion> queryList(ExQuestionQueryCriteria criteria) {
        return baseMapper.queryList(criteria);
    }

    @Override
    public List<ExQuestion> queryListSort(ExQuestionQueryCriteria criteria) {
        return baseMapper.queryListSort(criteria);
    }
}
